import {
  createAction,
  NavigationActions,
  Storage
} from '@utils'
import NavigationService from '@utils/navigation'
import { Toast } from '@ant-design/react-native';
import settings from '../settings'

import * as api from '@services/api'

export default {
  namespace: 'app',
  state: {
    
  },
  reducers: {
    updateState(state, {
      payload
    }) {
      return { 
        ...state,
        ...payload
      }
    },
  },
  effects: {
    * loadStorage(action, {
      call,
      put
    }) {
      const login = yield call(Storage.get, 'login', false)
      yield put(createAction('updateState')({
        login,
        loading: false
      }))
    },
    * login({
      payload
    }, {
      call,
      put
    }) {
      // yield put(createAction('updateState')({
      //   fetching: true
      // }))
      // const login = yield call(authService.login, payload)
      // if (login) {
      //   yield put(NavigationActions.back())
      // }
      // yield put(createAction('updateState')({
      //   login,
      //   fetching: false
      // }))
      // Storage.set('login', login)
      
      const { code } = yield call(api.login, payload)
      if (code === settings.code) {
        // NavigationService.navigate("Home")
        yield put(NavigationActions.navigate({ routeName: 'Home'}))
      } else {
        Toast.fail("用户名或密码错误")
      }
    },
    * logout(action, {
      call,
      put
    }) {
      yield call(Storage.set, 'login', false)
      yield put(createAction('updateState')({
        login: false
      }))
    },
  },
  subscriptions: {
    setup({
      dispatch
    }) {
      dispatch({
        type: 'loadStorage'
      })
    },
  },
}